<template>
	<div class="evaluate">
		<pubHead title="发表评论"></pubHead>
		<div class="evaluate-top flex" v-if="goodsInfo.ticket_name">
			<div class="evaluate-t-l">
				<img :src="goodsInfo.ticket_image" />
			</div>
			<div class="evaluate-t-r">
				<p class="t-r-1 twoline bold">{{goodsInfo.ticket_name}}</p>
				<p class="t-r-1 twoline" style="margin-top: 0.1rem;">{{goodsInfo.cate_name}}</p>
				<p class="t-r-2 twoline">{{goodsInfo.scenic_ticket_name}}</p>
			</div>
		</div>
		<div v-if="goodsInfo.sub">
			<div v-for="(item,index) in goodsInfo.sub" :key="index">
				
				<div class="evaluate-top flex" v-for="(item1,index1) in item.goods" :key="index1">
					<div class="evaluate-t-l">
						<img :src="item1.images" />
					</div>
					<div class="evaluate-t-r">
						<p class="t-r-1 twoline bold">{{item1.goods_name}}</p>
						<p class="t-r-1 twoline" style="margin-top: 0.3rem;">{{item1.key_name}}</p>
						<p class="t-r-2 twoline" style="color: orangered;">￥{{item1.goods_price}}</p>
					</div>
				</div>
			</div>
		</div>
		<div v-if="goodsInfo.goods">
			<div v-for="(item,index) in goodsInfo.goods" :key="index">
				
				<div class="evaluate-top flex" v-for="(item1,index1) in item.goods" :key="index1">
					<div class="evaluate-t-l">
						<img :src="item1.images" />
					</div>
					<div class="evaluate-t-r">
						<p class="t-r-1 twoline bold">{{item1.goods_name}}</p>
						<p class="t-r-1 twoline" style="margin-top: 0.3rem;">{{item1.key_name}}</p>
						<p class="t-r-2 twoline" style="color: orangered;">￥{{item1.goods_price}}</p>
					</div>
				</div>
			</div>
		</div>
		<div class="evaluate-center flex ali-c" style="border-bottom: 0.01rem solid #e3e3e3;">
			<span style="margin-right: 0.2rem;">整体评价</span><van-rate color="#ee0a24" void-icon="star" void-color="#eee" v-model="value" />
		</div>
		<div class="evaluate-footer">
			  <van-field rows="4" autosize v-model="content" type="textarea" placeholder="说说体验感受嘛，其他顾客想知道" />
		</div>
		<div style="background-color: #FFFFFF;padding: 0.2rem;border-bottom: 0.01rem solid #e3e3e3;">
			<van-uploader :before-delete="beforeDele" :after-read="afterRead"  v-model="fileList" multiple />
		</div>
		<div class="evaluate-click-top flex jus-e" @click="toEvaluate">
			<div class="evaluate-click">
				立即评价
			</div>
		</div>
	</div>
</template>

<script>
	import Vue from 'vue';
	import pubHead from '@/components/head';
	import { Rate } from 'vant';
	import { Field,Toast } from 'vant';
	import { Uploader } from 'vant';
	import {upLoad,Addevaluate} from '@/request/api.js'
	import Exif from "exif-js";
	Vue.use(Rate).use(Field).use(Uploader);
	export default{
		data(){
			return{
				value:5,
				content:'',
				fileList:[],
				goodsInfo:{},
				imgList:[],
				files:{
					name:"",
					type:""
				},
				picValue:null,
				headerImage: null,
				upImgUrl:null
			}
		},
		components:{
			 pubHead
		},
		created() {
			this.goodsInfo = this.$route.params
			console.log(this.goodsInfo)
		},
		methods:{
			postImg(){
				let that = this
				let file = this.dataURLtoFile(this.headerImage);
				let formData = new FormData();
				formData.append("file", file);
				this.$loading('图片上传中~')
				upLoad(formData).then(res=>{
				  if(res.code==1){
					  Toast.clear()
					 that.imgList.push(res.data)
					 console.log(that.imgList)
				  }else{
					  this.$tip('上传图片的格式有误！')
				  }
			  })
			},
			afterRead(file) {
				let that = this
				that.files.name = file.file.name;//获取文件名
				that.files.type = file.file.type;//获取类型
				that.picValue = file.file;//文件流
				that.imgPreview(that.picValue)
				// var formData = new FormData();
				// formData.append('file',file.file)
			 //      upLoad(formData).then(res=>{
				// 	  if(res.code==1){
				// 		 that.imgList.push(res.data)
				// 		 console.log(that.imgList)
				// 	  }else{
				// 		  this.$tip('上传图片的格式有误！')
				// 	  }
				//   })
			},
			 // 处理图片
			imgPreview(file) {
			  let self = this;
			  let Orientation;
			  //去获取拍照时的信息，解决拍出来的照片旋转问题
			  Exif.getData(file, function () {
				Orientation = Exif.getTag(this, "Orientation");
			  });
			  // 看支持不支持FileReader
			  if (!file || !window.FileReader){
				  self.$tip('你的手机不支持FileReader')
				  return;
			  } 
			  if (/^image/.test(file.type)) {
				// 创建一个reader
				let reader = new FileReader();
				// 将图片2将转成 base64 格式
				reader.readAsDataURL(file);
				// 读取成功后的回调
				reader.onloadend = function () {
				  // console.log(this.result);
				  let result = this.result;
				  let img = new Image();
				  img.src = result;
				  //判断图片是否大于500K,是就直接上传，反之压缩图片
				  if (this.result.length <= 500 * 1024) {
					self.headerImage = this.result;
					self.postImg();
				  } else {
					img.onload = function () {
					  let data = self.compress(img, Orientation);
					  self.headerImage = data;
					  self.postImg();
					};
				  }
				};
			  }
			},
			 compress(img, Orientation) {
			  let canvas = document.createElement("canvas");
			  let ctx = canvas.getContext("2d");
			  //瓦片canvas
			  let tCanvas = document.createElement("canvas");
			  let tctx = tCanvas.getContext("2d");
			  // let initSize = img.src.length;
			  let width = img.width;
			  let height = img.height;
			  //如果图片大于四百万像素，计算压缩比并将大小压至400万以下
			  let ratio;
			  if ((ratio = (width * height) / 4000000) > 1) {
				// console.log("大于400万像素");
				ratio = Math.sqrt(ratio);
				width /= ratio;
				height /= ratio;
			  } else {
				ratio = 1;
			  }
			  canvas.width = width;
			  canvas.height = height;
			  //    铺底色
			  ctx.fillStyle = "#fff";
			  ctx.fillRect(0, 0, canvas.width, canvas.height);
			  //如果图片像素大于100万则使用瓦片绘制
			  let count;
			  if ((count = (width * height) / 1000000) > 1) {
				// console.log("超过100W像素");
				count = ~~(Math.sqrt(count) + 1); //计算要分成多少块瓦片
				//      计算每块瓦片的宽和高
				let nw = ~~(width / count);
				let nh = ~~(height / count);
				tCanvas.width = nw;
				tCanvas.height = nh;
				for (let i = 0; i < count; i++) {
				  for (let j = 0; j < count; j++) {
					tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);
					ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
				  }
				}
			  } else {
				ctx.drawImage(img, 0, 0, width, height);
			  }
			  //修复ios上传图片的时候 被旋转的问题
			  if (Orientation != "" && Orientation != 1) {
				switch (Orientation) {
				  case 6: //需要顺时针（向左）90度旋转
					this.rotateImg(img, "left", canvas);
					break;
				  case 8: //需要逆时针（向右）90度旋转
					this.rotateImg(img, "right", canvas);
					break;
				  case 3: //需要180度旋转
					this.rotateImg(img, "right", canvas); //转两次
					this.rotateImg(img, "right", canvas);
					break;
				}
			  }
			  //进行最小压缩
			  let ndata = canvas.toDataURL("image/jpeg", 0.1);
			  tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
			  return ndata;
			},
			// 旋转图片
			rotateImg(img, direction, canvas) {
			  //最小与最大旋转方向，图片旋转4次后回到原方向
			  const min_step = 0;
			  const max_step = 3;
			  if (img == null) return;
			  //img的高度和宽度不能在img元素隐藏后获取，否则会出错
			  let height = img.height;
			  let width = img.width;
			  let step = 2;
			  if (step == null) {
				step = min_step;
			  }
			  if (direction == "right") {
				step++;
				//旋转到原位置，即超过最大值
				step > max_step && (step = min_step);
			  } else {
				step--;
				step < min_step && (step = max_step);
			  }
			  //旋转角度以弧度值为参数
			  let degree = (step * 90 * Math.PI) / 180;
			  let ctx = canvas.getContext("2d");
			  switch (step) {
				case 0:
				  canvas.width = width;
				  canvas.height = height;
				  ctx.drawImage(img, 0, 0);
				  break;
				case 1:
				  canvas.width = height;
				  canvas.height = width;
				  ctx.rotate(degree);
				  ctx.drawImage(img, 0, -height);
				  break;
				case 2:
				  canvas.width = width;
				  canvas.height = height;
				  ctx.rotate(degree);
				  ctx.drawImage(img, -width, -height);
				  break;
				case 3:
				  canvas.width = height;
				  canvas.height = width;
				  ctx.rotate(degree);
				  ctx.drawImage(img, -width, 0);
				  break;
			  }
			},
			//将base64转换为文件
			dataURLtoFile(dataurl) {
			  var arr = dataurl.split(","),
				bstr = atob(arr[1]),
				n = bstr.length,
				u8arr = new Uint8Array(n);
			  while (n--) {
				u8arr[n] = bstr.charCodeAt(n);
			  }
			  return new File([u8arr], this.files.name, {
				type: this.files.type
			  });
			},
			beforeDele(index,file){
				console.log(file)
				this.imgList.splice(file.index,1)
				return true
			},
			
			toEvaluate(){
				let that = this
				Addevaluate({
					token:localStorage.getItem('token'),
					order_id:that.goodsInfo.id,
					images:that.imgList.join(),
					content:that.content,
					star_num:that.value
				}).then(res=>{
					if(res.code==1){
						this.$tip('提交成功，稍后跳转到首页')
						setTimeout(()=>{
							that.$router.replace('/')
						},1000)
					}else{
						that.$tip(res.msg)
					}
				})
			}
		}
	}
</script>

<style lang="less">
	.evaluate{
		max-height: 750px;
		background-color: #f5f5f5;
		.evaluate-top{
			background-color: #fff;
			padding: 0.2rem;
			.evaluate-t-l{
				width: 1.8rem;
				height: 1.8rem;
				margin-right: 0.2rem;
				img{
					border-radius: 0.05rem;
				}
			}
			.evaluate-t-r{
				flex: 1;
				.t-r-1{
					color: #333333;
					font-size: 0.28rem;
				}
				.t-r-2{
					margin-top: 0.1rem;
					color: #999999;
					font-size: 0.24rem;
				}
			}
		}
		.evaluate-center{
			padding: 0.2rem;
			font-size: 0.3rem;
			color: #333333;
			background-color: #fff;
		}
		.evaluate-click-top{
			background-color: #fff;
			padding: 0.2rem;
		}
		.evaluate-click{
			border: 0.02rem solid #FEA382;
			color: #FEA382;
			border-radius: 0.1rem;
			width: 1.52rem;
			height: 0.5rem;
			line-height: 0.5rem;
			text-align: center;
		}
	}
</style>
